"use strict";

//form表单中的数据包装为json
function serializeObject(FormId) {
    var o = {};
    var a = $("#" + FormId).serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            if (this.value) {
                o[this.name].push(this.value);
            }
        } else {
            if (this.value) {
                o[this.name] = this.value;
            }
        }
    });
    return o;
}


//设置ajax请求结束后的执行动作
$.ajaxSetup({
    complete: function (XMLHttpRequest, textStatus, error) {
        var redirect = XMLHttpRequest.getResponseHeader("REDIRECT");
        if (redirect == "REDIRECT") {
            var win = window;
            while (win != win.top) {
                win = win.top;
            }
            //将后端重定向的地址取出来,使用win.location.href去实现重定向的要求
            layer.msg("登录超时请重新登录！", {icon: 5, time: 1500}, function () {
                win.location.href = XMLHttpRequest.getResponseHeader("CONTEXTPATH");
            })
        }
    },
    type: 'POST'
});

/**
 * post ajax
 * @param url
 * @param data
 * @param success
 * @param error
 */
function post(url, data, success, error) {
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        success: function (resp) {
            success(resp);
        },
        error: function (XHttpResponseText) {
            error(XHttpResponseText);
        }
    })
}

/**
 * get ajax
 * @param url
 * @param data
 * @param success
 * @param error
 */
function get(url, data, success, error) {
    $.ajax({
        url: url,
        type: 'GET',
        cache: false,
        data: data,
        success: function (resp) {
            success(resp);
        },
        error: function (XHttpResponseText) {
            error(XHttpResponseText);
        }
    })
}

/**
 * form 表单提交
 * @param url
 * @param data
 * @param success
 * @param error
 */
function form(url, data, success, error) {
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        success: function (resp) {
            success(resp);
        },
        error: function (XHttpResponseText) {
            error(XHttpResponseText);
        }
    })
}


function request(url, method, data, callback, error) {

    if (method == 0) {
        method = 'GET';
    } else if (method == 1) {
        method = 'POST';
    } else {
        method = 'GET';
    }

    var buttonId = $("button.btn");

    $.ajax({
        url: url,
        type: method,
        cache: false,
        data: data,
        beforeSend: function () {
            // 禁用按钮防止重复提交
            buttonId.attr({disabled: "disabled"});
        },
        success: function (resp) {
            callback(resp);
        },
        complete: function () {
            buttonId.removeAttr("disabled");
        },
        error: function (xhttpResponse) {
            error(xhttpResponse);
        }
    })
}

function requestAsync(url, method, data, callback, error) {

    if (method == 0) {
        method = 'GET';
    } else if (method == 1) {
        method = 'POST';
    } else {
        method = 'GET';
    }

    var buttonId = $("button.btn");

    $.ajax({
        url: url,
        type: method,
        cache: false,
        data: data,
        async: false,
        beforeSend: function () {
            // 禁用按钮防止重复提交
            buttonId.attr({disabled: "disabled"});
        },
        success: function (resp) {
            callback(resp);
        },
        complete: function () {
            buttonId.removeAttr("disabled");
        },
        error: function (xhttpResponse) {
            error(xhttpResponse);
        }
    })
}

/**
 * 函数填充表单数据
 */
function loadData(obj) {
//var obj = eval("("+jsonStr+")");
    var key, value, tagName, type, arr;
    for (x in obj) {
        key = x;
        value = obj[x];
        $("[name='" + key + "'],[name='" + key + "[]']").each(function () {
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if (tagName == 'INPUT') {
                if (type == 'radio') {
                    $(this).prop('checked', $(this).val() == value);
                } else if (type == 'checkbox') {
                    arr = value.split(',');
                    for (var i = 0; i < arr.length; i++) {
                        if ($(this).val() == arr[i]) {
                            $(this).prop('checked', true);
                            break;
                        }
                    }
                } else {
                    $(this).val(value);
                }
            } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
                $(this).val(value);
            }
        });
    }
}


/*校验字符串不为空且不包含空格*/
function check(str) {
    if ((str.replace(/(^\s*)|(\s*$)/g, "").length > 0 && str != null && str.indexOf(" ") == -1)) {
        return true;
    }
}

/*校验字符串不为空*/
function checkTirm(str) {
    if ((str.replace(/(^\s*)|(\s*$)/g, "").length > 0 && str != null)) {
        return true;
    }
}

/*校验字符串为正整数*/
function checkNum(str) {
    var flag = /^\+?[1-9][0-9]*$/;　　//正整数
    return flag.test(str);
}


function add(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
}

function sub(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e;
}

function mul(a, b) {
    var c = 0,
        d = a.toString(),
        e = b.toString();
    try {
        c += d.split(".")[1].length;
    } catch (f) {
    }
    try {
        c += e.split(".")[1].length;
    } catch (f) {
    }
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}

function div(a, b) {
    var c, d, e = 0,
        f = 0;
    try {
        e = a.toString().split(".")[1].length;
    } catch (g) {
    }
    try {
        f = b.toString().split(".")[1].length;
    } catch (g) {
    }
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
}

//从字典获取字典信息并进行下拉框初始化
function selectFormater(id, field) {
    var datas = [];
    //初始化字段信息
    var initData = function (data, defaultValue) {
        var htmlData = selectOptionInitDict(data, defaultValue);
        $("#" + id).html(htmlData);
    };
    //获取字典数组
    datas = getDictData(field, datas, initData, null);
    return datas;
}

//初始化元树；treeurl：请求路径；treeObjId:ztree树id；treeType：（0：单选，1多选,2:多选父节点不选），nameInputId：要显示名称的input框id；valueInputId：获取值的input框id, checkedNodes:zTree回显时的数据列表,以','分隔的字符串
function initTree(treeUrl, treeObjId, treeType, nameInputId, valueInputId, checkedNodes) {
    var zTreeEle;
    var setting;
    if (undefined == treeObjId || null == treeObjId) {
        treeObjId = "typeTree";
    }
    if (treeType == 0 || treeType == null) {
        setting = {
            data: {
                simpleData: {
                    enable: true, // 设置启用简单数据格式[{id, pId, name}, {id, pId, name}]
                    idKey: "id",  // 节点数据中保存唯一标识的属性名称
                    pIdKey: "pId",  // 节点数据中保存其父节点唯一标识的属性名称
                    rootPId: null  // 根节点id
                }
            },
            callback: {
                beforeClick: function (treeId, treeNode) {
                    if (treeType == null) {
                        if (treeNode.isParent) {
                            layer.msg("不能选择父节点");
                            return false;
                        }
                    }
                },
                onClick: function (e, treeId, treeNode) {
                    var selectedNodes = zTreeEle.getSelectedNodes();
                    var node = selectedNodes[0];
                    $("#" + nameInputId + "").val(node.name);
                    $("#" + valueInputId + "").val(node.id);
                }
            }

        };
    } else {
        setting = {
            check: {
                chkStyle: "checkbox",//复选框类型
                enable: true
            },
            data: {
                simpleData: {
                    enable: true, // 设置启用简单数据格式[{id, pId, name}, {id, pId, name}]
                    idKey: "id",  // 节点数据中保存唯一标识的属性名称
                    pIdKey: "pId",  // 节点数据中保存其父节点唯一标识的属性名称
                    rootPId: null  // 根节点id
                }
            },
            callback: {
                onCheck: function (e, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj(treeObjId);
                    var nodes = treeObj.getCheckedNodes(true);
                    var names = '';
                    var ids = '';
                    for (var i = 0; i < nodes.length; i++) {
                        if (treeType === 1) {
                            if (i === nodes.length - 1) {
                                names += nodes[i].name;
                                ids += nodes[i].id;
                            } else {
                                names += nodes[i].name + ",";
                                ids += nodes[i].id + ",";
                            }
                        }
                        if (treeType === 2) {
                            if (nodes[i].isParent !== true) {
                                if (i === nodes.length - 1) {
                                    names += nodes[i].name;
                                    ids += nodes[i].id;
                                } else {
                                    names += nodes[i].name + ",";
                                    ids += nodes[i].id + ",";
                                }
                            }
                        }
                    }
                    $("#" + nameInputId + "").val(names);
                    $("#" + valueInputId + "").val(ids)
                }
            }
        };
    }
    request(treeUrl, 0, null, function (data) {
        if (data.data != null) {
            var zTreeData = data.data;
            //多选回显
            if (treeType !== 0) {
                if (checkedNodes) {
                    var checkNodeArray = checkedNodes.split(',');
                    //todo 回显需要判断是否还有子节点
                    $.each(zTreeData, function (index, node) {
                        $.each(checkNodeArray, function (indexCheck, nodeCheck) {
                            if (node.id == nodeCheck) {
                                node["checked"] = true;
                            }
                        });
                    });
                }
            }
            zTreeEle = $.fn.zTree.init($("#" + treeObjId), setting, zTreeData);
        } else {
            layer.msg("获取树数据失败！")
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}


function openTree(divId) {
    layer.open({
        type: 1,
        area: '300px',
        title: '选择上级节点',
        shade: 0.6,
        shadeClose: true, //点击遮罩关闭层
        maxmin: false,
        anim: 1,
        btn: ['确定', '取消'],
        content: $('#' + divId),
        success: function (layero, index) {
            // layer.iframeAuto(index);
        },
        yes: function (index, layero) {
            layer.close(index);
        },
        btn2: function (index) {
            layer.close(index);
        },
        end: function (index) {
            // divId.hide();
            layer.close(index);
        }
    });
}